package com.kalvin.kvf.modules.ks.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kalvin.kvf.common.dto.R;
import com.kalvin.kvf.common.utils.ShiroKit;
import com.kalvin.kvf.modules.hxy.entity.Account;
import com.kalvin.kvf.modules.hxy.entity.Cookies;
import com.kalvin.kvf.modules.hxy.mapper.AccountMapper;
import com.kalvin.kvf.modules.hxy.mapper.CookiesMapper;
import com.kalvin.kvf.modules.ks.entity.KSIntentionCust;
import com.kalvin.kvf.modules.ks.entity.KSTask;
import com.kalvin.kvf.modules.ks.entity.KSVideo;
import com.kalvin.kvf.modules.ks.mapper.KSCookieMapper;
import com.kalvin.kvf.modules.ks.mapper.KSIntentionCustMapper;
import com.kalvin.kvf.modules.ks.mapper.KSTaskMapper;
import com.kalvin.kvf.modules.ks.mapper.KSVideoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.Objects;
import java.util.Random;

/**
 * <p>
 * 小红书登录信息的cookie 服务实现类
 * </p>
 * @since 2023-12-01 11:32:06
 */
@Service
public class KsCrawlerServiceImpl implements KsCrawlerService{
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private KSTaskMapper ksTaskMapper;
    @Autowired
    private KSVideoMapper ksVideoMapper;
    @Autowired
    private KSCookieMapper ksCookieMapper;
    @Autowired
    private KSIntentionCustMapper ksIntentionCustMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private CookiesMapper cookiesMapper;
//    @Bean
//    public RestTemplate restTemplate(RestTemplateBuilder builder) {
//        return builder.build();
//    }

    @Override
    @Async
    public R taskStart() throws InterruptedException, Exception {
        Random random = new Random();
        //查询当前任务意向获客数量
        KSTask ksTask = ksTaskMapper.selectOne(new QueryWrapper<KSTask>().eq("phone", ShiroKit.getUser().getUsername()).eq("task_status", 0));
        //更新任务状态
        ksTask.setTaskStatus(1);
        ksTaskMapper.updateById(ksTask);
        //获取当前用户的cookie
        Cookies ksCookie = cookiesMapper.selectOne(new QueryWrapper<Cookies>().eq("phone", ShiroKit.getUser().getUsername()).eq("medium_type",2).last("limit 1").lambda().orderByAsc(Cookies::getLastLoginTime));
        ksCookie.setLastLoginTime(LocalDateTime.now());
        cookiesMapper.updateById(ksCookie);
        int a = 0;
        String pcursor = "";
        long time = 0;
        long oneHourLaterTimestamp = 0;
        LocalDateTime now = LocalDateTime.now();
        //1小时后的时间戳
        LocalDateTime oneHourLater = now.plus(Duration.ofHours(1));
        oneHourLaterTimestamp = oneHourLater.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        while (a < ksTask.getCustNum() && !pcursor.equals("no_more")&&time<oneHourLaterTimestamp) {
            int randomNumber = random.nextInt(3000) + 2000;
            String url = "https://www.kuaishou.cn/graphql";
            //定义搜索视频请求header
            HttpHeaders httpHeaders=new HttpHeaders();
            httpHeaders.add("Content-Type","application/json");
            httpHeaders.add("Cookie",ksCookie.getCookies());
            httpHeaders.add("Host","www.kuaishou.cn");
            httpHeaders.add("Origin","https://www.kuaishou.cn");
            String encode = URLEncoder.encode(ksTask.getSearchKeyword(), "UTF-8");
            httpHeaders.add("Referer","https://www.kuaishou.cn/search/video?searchKey="+encode);
            httpHeaders.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");
            //定义请求搜索视频的body
            JSONObject requestBody = new JSONObject();
            requestBody.put("operationName", "visionSearchPhoto");
            requestBody.put("query", "fragment photoContent on PhotoEntity {__typename id duration  caption  originCaption  likeCount  viewCount  commentCount  realLikeCount  coverUrl  photoUrl  photoH265Url  manifest  manifestH265  videoResource  coverUrls {  url  __typename  }  timestamp  expTag  animatedCoverUrl  distance  videoRatio  liked  stereoType  profileUserTopPhoto  musicBlocked } fragment recoPhotoFragment on recoPhotoEntity {  __typename  id  duration  caption  originCaption  likeCount  viewCount  commentCount  realLikeCount  coverUrl  photoUrl  photoH265Url  manifest  manifestH265  videoResource  coverUrls {  url  __typename  }  timestamp  expTag  animatedCoverUrl  distance  videoRatio  liked  stereoType  profileUserTopPhoto  musicBlocked } fragment feedContent on Feed {  type  author {  id  name  headerUrl  following  headerUrls {   url   __typename  }  __typename  }  photo {  ...photoContent  ...recoPhotoFragment  __typename  }  canAddComment  llsid  status  currentPcursor  tags {  type  name  __typename  }  __typename } query visionSearchPhoto($keyword: String, $pcursor: String, $searchSessionId: String, $page: String, $webPageArea: String) {  visionSearchPhoto(keyword: $keyword, pcursor: $pcursor, searchSessionId: $searchSessionId, page: $page, webPageArea: $webPageArea) {  result  llsid  webPageArea  feeds {   ...feedContent   __typename  }  searchSessionId  pcursor  aladdinBanner {   imgUrl   link   __typename  }  __typename  } }");
            JSONObject variables = new JSONObject();
            variables.put("pcursor", pcursor);
            variables.put("keyword", ksTask.getSearchKeyword());
            variables.put("page", "search");
            requestBody.put("variables", variables);
            Thread.sleep(randomNumber);
            //发送请求
            HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), httpHeaders);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            // 获取响应结果
            String responseBody = response.getBody();
            //结果转json
            JSONObject jsonObject = JSON.parseObject(responseBody);
            //解析数据拿到authorId和photoId结果list
            JSONObject visionSearchPhoto = jsonObject.getJSONObject("data").getJSONObject("visionSearchPhoto");
            JSONArray feeds = visionSearchPhoto.getJSONArray("feeds");
            Object p = jsonObject.getJSONObject("data").getJSONObject("visionSearchPhoto").get("pcursor");
            pcursor = (String) p;
            //遍历视频list并发送请求访问详情获取评论
            for (Object o : feeds) {
                try {
                    String plPcursor = "";
                    KSVideo ksVideo=new KSVideo();
                    while (a < ksTask.getCustNum() && !plPcursor.equals("no_more")) {
                        int plrandomNumber = random.nextInt(2500) + 2000;
                        JSONObject feedsJson = JSON.parseObject(o.toString());
                        Object photoId = feedsJson.getJSONObject("photo").get("id");
                        String caption = (String) feedsJson.getJSONObject("photo").get("caption");
                        Object authorId = feedsJson.getJSONObject("author").get("id");
                        //定义搜索视频请求header
                        HttpHeaders headers = new HttpHeaders();
                        headers.add("Content-Type", "application/json");
                        headers.add("Cookie", "kpf=PC_WEB; clientid=3; did=web_c1bec1816da426f63f577c2ccb587303; userId=2631183018; kpn=KUAISHOU_VISION; kuaishou.server.web_st=ChZrdWFpc2hvdS5zZXJ2ZXIud2ViLnN0EqABBuNyQDdYiB_jPF2SDHBoe2UQIzCJ_5y06Q4tTSROyWbk46BCt4cTPJvE-bXYlakq1RmiqV40dX8NaJmmrU75VO4OEH9_FDqycrn8byAQiYHvpGVpPMlqlewsPCBSLXSz-_eOTVXv_0y_ao8TsI3IdCQ0l4z7WA-qyup6T0VgfPPbN1nF9aVmc8QMDDN80m9Q6XbBkjFjY_T4aj-7bSzyIRoStEyT9S95saEmiR8Dg-bb1DKRIiDpa49yM7KZHKybjZLdWT_gNZ0__sG--mo5R-zRRAFV6CgFMAE; kuaishou.server.web_ph=d6505cfd70f3d63c8c13eac6ba3663f633d1");
                        headers.add("Host", "www.kuaishou.cn");
                        headers.add("Origin", "https://www.kuaishou.cn");
                        headers.add("Referer", "https://www.kuaishou.cn/short-video/" + photoId + "?authorId=" + authorId + "&streamSource=search&area=searchxxnull&searchKey="+encode);
                        System.out.println("https://www.kuaishou.cn/short-video/" + photoId + "?authorId=" + authorId + "&streamSource=search&area=searchxxnull&searchKey="+encode);
                        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");
                        JSONObject body = new JSONObject();
                        body.put("operationName", "commentListQuery");
                        body.put("query", "query commentListQuery($photoId: String, $pcursor: String) { visionCommentList(photoId: $photoId, pcursor: $pcursor) { commentCount pcursor rootComments {  commentId  authorId  authorName  content  headurl  timestamp  likedCount  realLikedCount  liked  status  authorLiked  subCommentCount  subCommentsPcursor  subComments {  commentId  authorId  authorName  content  headurl  timestamp  likedCount  realLikedCount  liked  status  authorLiked  replyToUserName  replyTo  __typename  }  __typename } __typename } }");
                        JSONObject variable = new JSONObject();
                        variable.put("pcursor", plPcursor);
                        variable.put("photoId", photoId);
                        body.put("variables", variable);
                        KSVideo ksVideo1 = ksVideoMapper.selectOne(new QueryWrapper<KSVideo>().eq("task_id", ksTask.getId()).eq("video_link", "https://www.kuaishou.cn/short-video/" + photoId));
                        if (ksVideo1==null||ksVideo1.getSize()==0){
                            //视频数据写入库中
                            ksVideo.setTaskId(ksTask.getId());
                            ksVideo.setVideoLink("https://www.kuaishou.cn/short-video/" + photoId);
                            ksVideo.setDiggingTime(LocalDateTime.now());
                            ksVideo.setPhone(ShiroKit.getUser().getUsername());
                            ksVideo.setTaskName(ksTask.getName());
                            ksVideo.setCreateTime(LocalDateTime.now());
                            ksVideo.setLabel(caption);
                            ksVideoMapper.insert(ksVideo);
                        }
                        Thread.sleep(plrandomNumber);
                        //发送请求
                        HttpEntity<String> httpEntity = new HttpEntity<>(body.toString(), headers);
                        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
                        // 获取响应结果
                        String responseBody1 = responseEntity.getBody();
                        //结果转json
                        JSONObject jsonObject1 = JSON.parseObject(responseBody1);
                        JSONObject visionCommentList = jsonObject1.getJSONObject("data").getJSONObject("visionCommentList");
                        JSONArray rootComments = visionCommentList.getJSONArray("rootComments");
                        Object pcur = jsonObject1.getJSONObject("data").getJSONObject("visionCommentList").get("pcursor");
                        plPcursor = (String) pcur;
                        for (Object comments : rootComments) {
                            try{
                                JSONObject comment = JSON.parseObject(comments.toString());
                                String content=comment.getString("content");
                                String headurl = comment.getString("headurl");
                                String authorName = comment.getString("authorName");
                                long timestamp=comment.getLong("timestamp");
                                //取出关键字
                                String siftKeywords = ksTask.getSiftKeywords();
                                String[] siftKeywordsList = siftKeywords.split(",");
                                boolean siftContains = false;
                                //获取命中关键词
                                String keyword = null;
                                for (String s : siftKeywordsList) {
                                    siftContains = content.contains(s);
                                    if (siftContains) {
                                        keyword = s;
                                        break;
                                    }
                                }
                                if (siftContains && ksTask.getShieldKeywords() == null || siftContains && ksTask.getShieldKeywords().equals("")) {
                                    KSIntentionCust ksIntentionCust=new KSIntentionCust();
                                    ksIntentionCust.setTaskId(ksTask.getId());
                                    ksIntentionCust.setTaskName(ksTask.getName());
                                    ksIntentionCust.setVideoLink("https://www.kuaishou.cn/short-video/" + photoId);
                                    ksIntentionCust.setVideoId(ksVideo.getId());
                                    ksIntentionCust.setNickname(authorName);
                                    ksIntentionCust.setContent(content);
                                    ksIntentionCust.setPhone(ShiroKit.getUser().getUsername());
                                    ksIntentionCust.setCustAvatar(headurl);
                                    ksIntentionCust.setHitKeyword(keyword);
                                    ksIntentionCust.setAnalyseTime(LocalDateTime.now());
                                    ksIntentionCust.setCreateTime(LocalDateTime.now());
                                    ksIntentionCust.setCustHome("https://www.kuaishou.com/profile/"+authorId);
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String consuTime = sdf.format(new Date(timestamp));
                                    ksIntentionCust.setConsuTime(consuTime);
                                    ksIntentionCust.setVideoId(ksVideo.getId());
                                    ksIntentionCust.setLabel(caption);
                                    ksIntentionCustMapper.insert(ksIntentionCust);
                                }
                                if (siftContains && ksTask.getShieldKeywords() != null && !ksTask.getShieldKeywords().equals("")) {
                                    //取出屏蔽关键词
                                    String shieldKeywords = ksTask.getShieldKeywords();
                                    String[] shieldKeywordsList = shieldKeywords.split(",");
                                    boolean shieldContains = false;
                                    for (String s : shieldKeywordsList) {
                                        shieldContains = content.contains(s);
                                        if (shieldContains) {
                                            break;
                                        }
                                    }
                                    if (!shieldContains) {
                                        KSIntentionCust ksIntentionCust=new KSIntentionCust();
                                        ksIntentionCust.setTaskId(ksTask.getId());
                                        ksIntentionCust.setTaskName(ksTask.getName());
                                        ksIntentionCust.setVideoLink("https://www.kuaishou.cn/short-video/" + photoId + "?authorId=" + authorId + "&streamSource=search&area=searchxxnull&searchKey=" + encode);
                                        ksIntentionCust.setVideoId(ksVideo.getId());
                                        ksIntentionCust.setNickname(authorName);
                                        ksIntentionCust.setContent(content);
                                        ksIntentionCust.setPhone(ShiroKit.getUser().getUsername());
                                        ksIntentionCust.setHitKeyword(keyword);
                                        ksIntentionCust.setCustAvatar(headurl);
                                        ksIntentionCust.setAnalyseTime(LocalDateTime.now());
                                        ksIntentionCust.setCreateTime(LocalDateTime.now());
                                        ksIntentionCust.setCustHome("https://www.kuaishou.com/profile/"+authorId);
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        String consuTime = sdf.format(new Date(timestamp));
                                        ksIntentionCust.setConsuTime(consuTime);
                                        ksIntentionCust.setVideoId(ksVideo.getId());
                                        ksIntentionCust.setLabel(caption);
                                        ksIntentionCustMapper.insert(ksIntentionCust);
                                    }
                                }

                                Integer count = ksIntentionCustMapper.selectCount(new QueryWrapper<KSIntentionCust>().eq("task_id", ksTask.getId()));
                                if (Objects.equals(count, ksTask.getCustNum())) {
                                    break;
                                }

                            }catch (Exception e){
                                System.out.println("写入某个评论时错误，跳出错误继续执行");
                            }
                        }

                        Integer count= ksIntentionCustMapper.selectCount(new QueryWrapper<KSIntentionCust>().eq("task_id", ksTask.getId()));
                        if (Objects.equals(count, ksTask.getCustNum())){
                            break;
                        }
                    }

                    Integer integer = ksIntentionCustMapper.selectCount(new QueryWrapper<KSIntentionCust>().eq("video_id", ksVideo.getId()));
                    ksVideo.setVideoCustNum(integer);
                    ksVideoMapper.updateById(ksVideo);
                } catch (Exception e) {
                    System.out.println("异常跳出当前循环 继续执行");
                }
                Integer count= ksIntentionCustMapper.selectCount(new QueryWrapper<KSIntentionCust>().eq("task_id", ksTask.getId()));
                if (Objects.equals(count, ksTask.getCustNum())){
                    break;
                }
            }
            //执行结束后查一下客户库数量是否满足意向客户数量
            a = ksIntentionCustMapper.selectCount(new QueryWrapper<KSIntentionCust>().eq("task_id", ksTask.getId()));
            //获取当前时间戳
            LocalDateTime now2 = LocalDateTime.now();
            time= now2.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        }
        Integer count = ksIntentionCustMapper.selectCount(new QueryWrapper<KSIntentionCust>().eq("task_id", ksTask.getId()));
        ksTask.setUseCustNum(count);
        ksTaskMapper.updateById(ksTask);
        //减掉account的额度
        //获取当前用户信息
        Account account = accountMapper.selectById(ksTask.getAccountId());
        if (account.getCustNum() != null && account.getCustNum() > 0) {
            Account account2 = accountMapper.selectById(ksTask.getAccountId());
            Integer i = account2.getCustNum() - count;
            account2.setCustNum(i);
            accountMapper.updateById(account2);
        }
        return R.ok();
    }
}
